package com.hjy.imageloader.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.zhy.imageloader.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;

public class ImageListActivity extends Activity {

	GridView mGridView;
	ArrayList<String> mdata = new ArrayList<String>();
	List<File> files = new ArrayList<File>();
	ImageListAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_list);
		mGridView = (GridView) findViewById(R.id.id_gridView);
		mAdapter = new ImageListAdapter(this, mdata);
		mGridView.setAdapter(mAdapter);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			Toast.makeText(this, "无法获取", Toast.LENGTH_SHORT).show();
			return;
		}
		switch (requestCode) {
		case 1: {
			if (data != null) {
				Bundle selectedImageUri = data.getExtras();
				if (selectedImageUri == null) {
					return;
				}
				ArrayList<String> imageStrings = selectedImageUri.getStringArrayList("files");
				if (imageStrings != null && imageStrings.size() > 0) {
					for (String pathString : imageStrings) {
						mdata.add(0, pathString);
						files.add(new File(pathString));
					}
					mAdapter.notifyDataSetChanged();
				}
			}

		}
			break;
		default:
			break;

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void onClick(View view) {
		if (view.getId() == R.id.btn_upload) {
			if (files.size() == 0) {
				Toast.makeText(this, "尚未选择图片！", Toast.LENGTH_LONG).show();
				return;
			}
			RequestQueue mRequestQueue = Volley.newRequestQueue(this);
			String url = "http://192.168.1.108:8080/pic/pictest/pic/uploadFiles";

			MultipartRequest request = new MultipartRequest(url, error, listener, "files", files, null);
			mRequestQueue.add(request);
		}
	}

	Response.ErrorListener error = new ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError arg0) {
			showToast("error "+arg0.getMessage());
		}
	};
	Response.Listener<String> listener = new Response.Listener<String>() {
		@Override
		public void onResponse(String arg0) {
			showToast("success");
		}
	};

	public void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
		if(msg!=null)
		Log.e("ImageListActivity", msg);
	}
}
